<template>
  <div>
    <h1>商品列表</h1>
    <!-- 查询 -->
    <el-form :inline="true" :model="listFrom" class="demo-form-inline">
      <el-form-item label="商品名称/关键字/id">
        <el-input
          v-model="listFrom.keyWord"
          placeholder="请输入商品名称/关键字/id"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="list()">查询</el-button>
        <el-button type="danger" @click="onDeleteProdList()"
          >批量删除</el-button
        >
        <el-button type="info" @click="showAddProd()">添加商品</el-button>
      </el-form-item>
    </el-form>
    <!-- 列表 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="prodId" label="商品id" />
      <el-table-column prop="prodSpu" label="SPU" />
      <el-table-column prop="kindName" label="商品类型" />
      <el-table-column prop="typeName" label="商品分类" />
      <el-table-column prop="prodName" label="商品名称" />
      <el-table-column prop="brandName" label="商品品牌" />
      <el-table-column prop="prodStatus" label="商品状态" />
      <el-table-column prop="createBy" label="创建人" />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column prop="updateBy" label="更新人" />
      <el-table-column prop="updateTime" label="更新时间" />
      <el-table-column prop="unitName" label="商品单位" />
      <el-table-column prop="tagName" label="商品标签" />
      <el-table-column prop="appr" label="供应商" />
      <el-table-column prop="prodImage" label="缩略图">
        <template #default="scope">
          <el-image
            :src="scope.row.prodImage"
            v-if="scope.row.prodImage != null"
            style="width: 100px; height: 100px"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="info" size="small" @click="OnPRodAddList(scope.row)"
            >商品附件</el-button
          >
          <el-button type="success" @click="toProdDetail(scope.row.prodId)"
            >商品详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="demo-pagination-block">
      <div class="demonstration"></div>
      <el-pagination
        v-model:current-page="listFrom.pageNum"
        v-model:page-size="listFrom.pageSize"
        :page-sizes="[2, 4, 6, 8]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 添加商品 -->
    <div>
      <el-dialog v-model="dialogFormVisible" title="添加商品页面" width="900">
        <el-form
          ref="ruleFormRef"
          style="max-width: 600px"
          :model="form"
          :rules="rules"
          label-width="auto"
        >
          <el-form-item label="SPU" prop="prodSpu">
            <el-input v-model="form.prodSpu" />
          </el-form-item>
          <el-form-item label="商品类型" prop="prodKind">
            <el-radio-group v-model="form.prodKind">
              <el-radio
                v-for="item in kindList"
                :value="item.dictValue"
                :key="item.dictType"
                >{{ item.dictName }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item label="商品分类" prop="prodType">
            <el-tree-select
              v-model="form.prodType"
              :data="typeList"
              :render-after-expand="false"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="商品名称" prop="prodName">
            <el-input v-model="form.prodName" />
          </el-form-item>
          <el-form-item label="商品品牌" prop="brandId">
            <el-select
              v-model="form.brandId"
              placeholder="请选择商品品牌"
              style="width: 240px"
            >
              <el-option
                v-for="item in brandlist"
                :key="item.brandId"
                :label="item.brandName"
                :value="item.brandId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商品单位" prop="unitId">
            <el-select
              v-model="form.unitId"
              placeholder="请选择商品单位"
              style="width: 240px"
            >
              <el-option
                v-for="item in unitList"
                :key="item.dictId"
                :label="item.dictName"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商品标签" prop="tagId">
            <el-select
              v-model="form.tagId"
              placeholder="请选择商品标签"
              style="width: 240px"
            >
              <el-option
                v-for="item in tagList"
                :key="item.dictId"
                :label="item.dictName"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="供应商" prop="appr">
            <el-input v-model="form.appr" />
          </el-form-item>
          <el-form-item label="缩略图" prop="prodImage">
            <el-upload
              class="avatar-uploader"
              action="http://localhost:10010/prod/type/uploadFile"
              :headers="headers"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
            >
              <img v-if="form.prodImage" :src="form.prodImage" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              添加
            </el-button>
            <el-button @click="dialogFormVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
    <!-- 商品附件页面 -->
    <div>
      <el-dialog
        v-model="dialogTableVisible"
        title="添加商品附件页面"
        width="900"
      >
        <el-form
          ref="ruleFormRef"
          :model="ProdArrtForm"
          :rules="attarules"
          label-width="auto"
        >
          <el-form-item
            label="商品轮播图片"
            :label-width="formLabelWidth"
            prop="fileList"
          >
            <el-upload
              v-model:file-list="ProdArrtForm.fileList"
              action="http://localhost:10010/prod/type/uploadFile"
              :headers="headers"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
            <el-dialog v-model="dialogVisible">
              <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
          </el-form-item>
          <el-form-item label="商品视频" :label-width="formLabelWidth">
            <el-upload
              v-model:file-list="vileList"
              class="upload-demo"
              action="http://localhost:10010/prod/type/uploadFile"
              multiple
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :headers="headers"
              :before-remove="beforeRemove"
              :limit="1"
              :on-exceed="handleExceed"
            >
              <el-button type="primary">上传视频</el-button>
              <template #tip>
                <div class="el-upload__tip">
                  作用于商品详情页顶部轮插的视频介绍,最大限制20MB.
                </div>
              </template>
            </el-upload>
          </el-form-item>
          <el-form-item
            label="上架时间"
            :label-width="formLabelWidth"
            prop="upFlag"
          >
            <el-radio-group v-model="ProdArrtForm.upFlag">
              <el-radio value="0" size="large">立即上架</el-radio>
              <el-radio value="1" size="large">定时下架</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label=""
            :label-width="formLabelWidth"
            v-if="ProdArrtForm.upFlag == 1"
          >
            <el-date-picker
              v-model="ProdArrtForm.upTime"
              type="dateTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择定时上架时间"
            />
          </el-form-item>
          <el-form-item
            label="定时下架"
            :label-width="formLabelWidth"
            prop="downFlag"
          >
            <el-switch
              v-model="ProdArrtForm.downFlag"
              :active-action-icon="View"
              :inactive-action-icon="Hide"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
          <el-form-item
            label=""
            :label-width="formLabelWidth"
            v-if="ProdArrtForm.downFlag == 1"
          >
            <el-date-picker
              v-model="ProdArrtForm.downTime"
              type="dateTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择定时下架时间"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="OnSubmitForm(ruleFormRef)">
              添加
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import {
  getProdList,
  deleteProdBatch,
  getSelectTypeListTree,
  getDictList,
  getBrand,
  addProdList,
  addAttaList,
} from "../api/api";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";
import type { UploadProps } from "element-plus";
import type { UploadUserFile } from "element-plus";
import { Hide, View } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
const router = useRouter();
const tableData = ref([]);
const typeList = ref([]);
const kindList = ref([]);
const brandlist = ref([]);
const unitList = ref([]);
const tagList = ref([]);
const listFrom = ref({
  pageNum: 1,
  pageSize: 2,
  keyWord: "",
});
//添加商品
const form = ref({
  appr: "",
  brandId: null,
  prodId: null,
  prodImage: "",
  prodKind: null,
  prodName: "",
  prodSpu: "",
  prodType: null,
  tagId: null,
  unitId: null,
});
//添加附件
const ProdArrtForm = ref({
  upFlag: null,
  downFlag: null,
  upTime: null,
  downTime: null,
  attaImages: null,
  attaVideo: null,
  prodId: null,
  fileList: [],
});
const total = ref(0);
const dialogFormVisible = ref(false);
const dialogTableVisible = ref(false);
const formLabelWidth = "140px";
//列表
const list = () => {
  getProdList(listFrom.value).then((res) => {
    if (res.data.code == 200) {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};
//分页
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  listFrom.value.pageSize = val;
  list();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  listFrom.value.pageNum = val;
  list();
};
//批量删除
const multipleSelection = ref<any[]>([]);
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
};
const onDeleteProdList = () => {
  let ids = [];
  if (multipleSelection.value.length == 0) {
    ElMessage.error("请选择你要删除的商品");
    return;
  }
  multipleSelection.value.forEach((item) => {
    ids.push(item.prodId);
  });
  ElMessageBox.confirm(
    "数据一旦删除就无法恢复，您确定要继续进行删除吗?",
    "删除警告框",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "error",
    }
  )
    .then(() => {
      deleteProdBatch(ids).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("删除成功");
          list();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "用户已取消操作",
      });
    });
};
//添加商品
const showAddProd = () => {
  dialogFormVisible.value = true;
};
//上传图片
const imageUrl = ref("");
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  form.value.prodImage = response.data;
};
const headers = ref({
  token: window.sessionStorage.getItem("token"),
});
//校验
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  appr: [{ required: true, message: "请输入供应商", trigger: "blur" }],
  brandId: [{ required: true, message: "请选择商品品牌", trigger: "blur" }],
  prodImage: [{ required: true, message: "请选择商品图片", trigger: "blur" }],
  prodKind: [{ required: true, message: "请选择商品类型", trigger: "blur" }],
  prodName: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  prodSpu: [{ required: true, message: "请输入商品SPU", trigger: "blur" }],
  prodType: [{ required: true, message: "请选择商品分类", trigger: "blur" }],
  tagId: [{ required: true, message: "请选择标签", trigger: "blur" }],
  unitId: [{ required: true, message: "请选择单位", trigger: "blur" }],
});
const attarules = reactive<FormRules>({
  upFlag: [{ required: true, message: "请选择上架状态", trigger: "blur" }],
  downFlag: [{ required: true, message: "请选择下架状态", trigger: "blur" }],
  fileList: [
    { required: true, message: "请上传商品轮播图片", trigger: "blur" },
  ],
});
//添加
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      addProdList(form.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("添加成功");
          dialogFormVisible.value = false;
          list();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};
//添加附件
const OnSubmitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      const attaImagesList = ref([]);
      ProdArrtForm.value.fileList.forEach((item) => {
        attaImagesList.value.push(item.response.data);
      });
      ProdArrtForm.value.attaImages = JSON.stringify(attaImagesList);
      if (vileList.value.length <= 0) {
        ElMessage.error("请上传商品视频");
        return;
      }
      ProdArrtForm.value.attaVideo = vileList.value[0].response.data;
      addAttaList(ProdArrtForm.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("添加商品附件成功");
          dialogTableVisible.value = false;
          list();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};
//轮播图片
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};
//商品视频
const vileList = ref<UploadUserFile[]>([]);
const handlePreview: UploadProps["onPreview"] = (uploadFile) => {
  console.log(uploadFile);
};
const handleExceed: UploadProps["onExceed"] = (files, uploadFiles) => {
  ElMessage.warning(
    `The limit is 3, you selected ${files.length} files this time, add up to ${
      files.length + uploadFiles.length
    } totally`
  );
};
const beforeRemove: UploadProps["beforeRemove"] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `Cancel the transfer of ${uploadFile.name} ?`
  ).then(
    () => true,
    () => false
  );
};
//商品附件
const OnPRodAddList = (row: any) => {
  dialogTableVisible.value = true;
  ProdArrtForm.value = {
    upFlag: null,
    downFlag: null,
    upTime: null,
    downTime: null,
    attaImages: null,
    attaVideo: null,
    prodId: null,
  };
  ProdArrtForm.value.prodId = row.prodId;
};
//商品详情
const toProdDetail = (prodId: number) => {
  router.push("/home/prodDetail/" + prodId);
};
onMounted(() => {
  list();
  //树形菜单
  getSelectTypeListTree().then((res) => {
    if (res.data.code == 200) {
      typeList.value = res.data.data;
    }
  });
  getDictList(1).then((res) => {
    if (res.data.code == 200) {
      kindList.value = res.data.data;
    }
  });
  getDictList(2).then((res) => {
    if (res.data.code == 200) {
      unitList.value = res.data.data;
    }
  });
  getDictList(3).then((res) => {
    if (res.data.code == 200) {
      tagList.value = res.data.data;
    }
  });
  getBrand().then((res) => {
    if (res.data.code == 200) {
      brandlist.value = res.data.data;
    }
  });
});
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
